<template>
  <div id="businessManage">
    <!-- 搜索框-->
    <business-search
      :show-search="showSearch"
      @handle-query="handleQuery($event)"
      @handle-reset="handleQuery({}, true)"
    ></business-search>
    <!-- 列表 -->
    <el-card shadow="never">
      <!-- 表格工具栏 -->
      <div class="toolbar">
        <!-- 左侧工具栏 -->
        <div>
          <el-button
            :disabled="removeIdList.length === 0"
            :icon="Delete"
            type="danger"
            @click="handleBatchDel"
          >
            批量删除
          </el-button>
          <el-button :icon="Download" @click="handleExport"> 导出</el-button>
        </div>
        <!-- 右侧工具栏 -->
        <div>
          <el-button
            :icon="Refresh"
            circle
            title="刷新"
            @click="handleQuery({}, true)"
          />
          <el-popover placement="bottom" trigger="click">
            <template #reference>
              <el-button :icon="Operation" circle title="筛选列" />
            </template>
            <el-scrollbar max-height="350px">
              <template v-for="col in cols" :key="col.props">
                <el-checkbox v-model="col.show" :label="col.label" />
              </template>
            </el-scrollbar>
          </el-popover>
          <el-button
            :icon="Search"
            circle
            title="搜索"
            @click="handleSearchShow"
          ></el-button>
        </div>
      </div>
      <!-- 列表 -->
      <el-table
        :data="tableData"
        border
        highlight-current-row
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('id')"
          align="center"
          label="数据Id"
          prop="id"
          show-overflow-tooltip
          width="150"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('username')"
          align="center"
          label="账号"
          prop="username"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('storeName')"
          align="center"
          label="店铺名"
          prop="storeName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('avatar')"
          align="center"
          label="头像"
          prop="avatar"
        >
          <template #default="scope">
            <el-image
              v-if="scope.row.avatar"
              :preview-src-list=" [scope.row.avatar as string] "
              :src="scope.row.avatar"
              preview-teleported
            />
            <el-image
              v-else
              :preview-src-list="[
                'https://picbed.shibalover.love/img/author.jpg',
              ]"
              preview-teleported
              src="https://picbed.shibalover.love/img/author.jpg"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('phone')"
          align="center"
          label="联系电话"
          min-width="150"
          prop="phone"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.phone || "无" }}
            <copy-button
              v-if="scope.row.phone"
              :index="scope.row.phone"
              :value="scope.row.phone"
            ></copy-button>
          </template>
        </el-table-column>

        <el-table-column
          v-if="handleColShow('businessStatus')"
          align="center"
          label="店铺状态"
          min-width="150"
          prop="'businessStatus"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              v-for="item in getBusinessStatusMsg(scope.row.businessStatus)"
              :key="item.value"
            >
              <el-tag :type="item.type"> {{ item.label }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('email')"
          align="center"
          label="联系邮箱"
          min-width="150"
          prop="email"
        >
          <template #default="scope">
            {{ scope.row.email || "无" }}
            <copy-button
              v-if="scope.row.email"
              :index="scope.row.email"
              :value="scope.row.email"
            ></copy-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('status')"
          align="center"
          label="状态"
          prop="status"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            <el-popconfirm
              :icon="InfoFilled"
              cancel-button-text="取消"
              confirm-button-text="确定"
              icon-color="#626AEF"
              title="确定要修改当前状态?"
              width="220"
              @confirm="switchStatus(scope.row)"
            >
              <template #reference>
                <el-switch
                  :model-value="scope.row.status == 1"
                  active-text="正常"
                  class="ml-2"
                  inactive-text="禁用"
                  inline-prompt
                  style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  "
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column
          v-if="handleColShow('place')"
          align="center"
          label="发货地"
          prop="place"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('createTime')"
          align="center"
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column
          v-if="handleColShow('updateTime')"
          align="center"
          label="修改时间"
          prop="updateTime"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.businessStatus === 1"
              class="box-item"
              content="审核商家"
              effect="dark"
              placement="bottom"
            >
              <el-button
                :icon="Stamp"
                circle
                size="small"
                type="warning"
                @click="handleValidatingShow(scope.row)"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              content="删除"
              effect="dark"
              placement="bottom"
            >
              <el-button
                :icon="Delete"
                circle
                size="small"
                type="danger"
                @click="handleDel(scope.row.id)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-scrollbar>
        <div class="pagination">
          <el-pagination
            :page-size="queryData.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="parseInt(total)"
            background
            layout="prev,pager,next,jumper,total,sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-scrollbar>
    </el-card>

    <!-- 审核商家弹窗-->
    <el-drawer
      v-model="validatingVisible"
      :before-close="handleValidatingClose"
      direction="rtl"
      size="40%"
    >
      <template #header="{ titleClass }">
        <div
          :class="titleClass"
          style="text-align: center; font-size: 20px; font-weight: bold"
        >
          商家审核
        </div>
      </template>
      <!-- 滚动 -->
      <el-scrollbar max-height="80vh">
        <!-- 表单 -->
        <el-form
          :model="selectData"
          disabled
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="店铺名" prop="storeName">
                <el-input
                  v-model="selectData.storeName"
                  clearable
                  placeholder="请输入店铺名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="头像" prop="avatar">
                <upload-image :urls="[selectData.avatar]"></upload-image>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="店铺简述" prop="sketch">
                <el-input
                  v-model="selectData.sketch"
                  clearable
                  maxlength="50"
                  placeholder="请输入店铺简述"
                  show-word-limit
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="联系号码" prop="phone">
                <el-input
                  v-model="selectData.phone"
                  clearable
                  placeholder="请输入联系号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="email">
                <template #label>
                  <span>联系邮箱</span>
                  <el-tooltip
                    content="邮箱将用于审核结果的发送，请验证是否能正常接收系统信息"
                    placement="left"
                  >
                    <el-icon style="margin: auto 0">
                      <InfoFilled />
                    </el-icon>
                  </el-tooltip>
                </template>

                <el-input
                  v-model="selectData.email"
                  clearable
                  placeholder="请输入联系邮箱"
                  style="width: 75%; margin-right: 5px"
                ></el-input>
                <el-button type="primary">验证</el-button>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="发货地" prop="place">
                <el-input
                  v-model="selectData.place"
                  clearable
                  placeholder="请输入联系邮箱"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="qualification">
                <template #label>
                  <span>资质证明</span>
                  <el-tooltip
                    content="上传营业资质等信息审核，最多上传4张证明"
                    placement="left"
                  >
                    <el-icon style="margin: auto 0">
                      <InfoFilled />
                    </el-icon>
                  </el-tooltip>
                </template>
                <el-scrollbar :max-height="200">
                  <upload-image
                    :index="1"
                    :urls="JSON.parse(selectData.qualification)"
                    style="width: 50%"
                  ></upload-image>
                </el-scrollbar>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button
            :loading="validateLoadFlag"
            type="primary"
            @click="handleValidateSubmit(true)"
            >通过
          </el-button>
          <el-button @click="handleValidateSubmit(false)">不通过</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 审核失败理由弹窗-->
    <el-dialog
      v-model="failVisible"
      draggable
      overflow
      title="Tips"
      width="500"
    >
      <el-input
        v-model="connect"
        clearable
        placeholder="请输入审核失败理由"
        type="textarea"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="failVisible = false">取消</el-button>
          <el-button
            :loading="validateLoadFlag"
            type="primary"
            @click="handleFailSubmit"
          >
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  Delete,
  Download,
  InfoFilled,
  Operation,
  Refresh,
  Search,
  Stamp,
} from "@element-plus/icons-vue";
import BusinessSearch from "@/views/back/system/business/components/BusinessSearch.vue";
import { ref } from "vue";
import {
  BusinessControllerService,
  BusinessQueryParams,
  BusinessVO,
} from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import CopyButton from "@/components/CopyButton.vue";
import { handleExportResponse } from "@/util/FileUtil";
import UploadImage from "@/components/UploadImage.vue";

/**
 * 查询搜索开始
 */
const queryInit = {
  pageNum: 1,
  pageSize: 10,
  beginTime: "",
  endTime: "",
  keyword: "",
  businessStatus: 4,
};
//查询数据对象
const queryData = ref({ ...queryInit });

//查询事件
function handleQuery(query: BusinessQueryParams, reset?: boolean) {
  //处理时间函数
  if (query?.createTime) {
    queryData.value.beginTime = query.createTime[0];
    queryData.value.endTime = query.createTime[1];
  }
  if (query?.keyword) {
    queryData.value.keyword = query.keyword;
  }
  if (query?.businessStatus) {
    queryData.value.businessStatus = query.businessStatus;
  }
  //重置页码
  if (reset) {
    queryData.value = { ...queryInit };
  }
  let data = queryData.value;
  console.log("查询条件：", data);
  BusinessControllerService.queryBusinessPageUsingGet(
    data.pageNum,
    data.pageSize,
    data.beginTime,
    data.businessStatus,
    data.endTime,
    data.keyword
  ).then((res) => {
    const { data } = res;
    total.value = data?.total || 0;
    tableData.value = data?.rows || [];
  });
}

// 页面创建时调用
handleQuery({});
//查询的数据
const total = ref<number>(0); //总条数
const tableData = ref<BusinessVO[]>([]); // 数据集合
const businessStatusOptions = [
  {
    label: "禁用",
    value: 0,
    type: "danger",
  },
  {
    label: "审核中",
    value: 1,
    type: "primary",
  },
  {
    label: "审核失败",
    value: 2,
    type: "warning",
  },
  {
    label: "正常",
    value: 3,
    type: "success",
  },
  {
    label: "全部",
    value: 4,
    type: "info",
  },
];

// 处理店铺状态
function getBusinessStatusMsg(value: number) {
  return businessStatusOptions.filter((item) => item.value === value);
}

//页面显示条数变化
function handleSizeChange(value: number) {
  queryData.value.pageSize = value;
  handleQuery({});
}

//页码变化
function handleCurrentChange(value: number) {
  queryData.value.pageNum = value;
  handleQuery({});
}

/**
 * 查询数据结束
 */

/**
 * 工具栏开始
 *
 */
// 2、批量删除开始
const selectionList = ref<Array<BusinessVO>>(); //选中的数据集合
const removeIdList = ref<number[]>([]); //选中的数据Id集合
function handleSelectionChange(value: BusinessVO[]) {
  console.log("选中的数据", value);
  selectionList.value = value;
  //获取选中的数据id
  removeIdList.value = value.map((item) => item.id!);
  console.log("选中的数据ID", removeIdList.value);
}

//批量删除事件
function handleBatchDel() {
  ElMessageBox.confirm(
    "确定要删除选中的" + removeIdList.value?.length + "条数据吗？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      BusinessControllerService.delBusinessUsingDelete(removeIdList.value).then(
        (res) => {
          ElMessage.success(res.data);
          handleQuery({}, true);
        }
      );
    })
    .catch(() => {
      ElMessage.info("取消删除！");
    });
}

// 2、批量删除结束
// 4、导出开始
function handleExport() {
  let data = queryData.value;
  BusinessControllerService.exportBusinessUsingGet(
    data.pageNum,
    data.pageSize,
    data.beginTime,
    data.businessStatus,
    data.endTime,
    data.keyword
  ).then((res) => {
    handleExportResponse(res);
  });
}

// 4、导出结束
// 6、筛选列开始
//列数据
const cols = ref([
  {
    label: "数据Id",
    props: "id",
    show: false,
  },
  {
    label: "账户",
    props: "username",
    show: true,
  },
  {
    label: "店铺名",
    props: "storeName",
    show: true,
  },
  {
    label: "头像",
    props: "avatar",
    show: false,
  },
  {
    label: "联系电话",
    props: "phone",
    show: true,
  },
  {
    label: "联系邮箱",
    props: "email",
    show: false,
  },
  {
    label: "店铺状态",
    props: "businessStatus",
    show: true,
  },
  {
    label: "店铺简述",
    props: "sketch",
    show: true,
  },
  {
    label: "发货地",
    props: "place",
    show: true,
  },
  {
    label: "账号状态",
    props: "status",
    show: true,
  },
  {
    label: "创建时间",
    props: "createTime",
    show: true,
  },
  {
    label: "修改时间",
    props: "updateTime",
    show: true,
  },
]);

//列展示处理
function handleColShow(prop: string) {
  return cols.value.filter((col) => col.props === prop)[0].show;
}

// 6、筛选列结束
// 7、搜索展示开始
//搜索展示处理
const showSearch = ref(true);

function handleSearchShow() {
  showSearch.value = !showSearch.value;
}

// 7、搜索展示结束
/**
 * 工具栏结束
 * 表格操作开始
 */

// 1、修改商家状态开始
const switchStatus = (row: any) => {
  const status = row.status === 1 ? 0 : 1;
  BusinessControllerService.updateBusinessAccountStaticUsingPut({
    id: row.id,
    status: status,
  }).then((res) => {
    ElMessage.success(res.data);
    handleQuery({}, true);
  });
};
// 1、修改商家状态结束
// 选中的数据
const selectData = ref<BusinessVO>({});
// 3、审核商家内容开始
const validatingVisible = ref(false); //编辑弹窗显示标志
// 打开展示弹窗
function handleValidatingShow(row: BusinessVO) {
  selectData.value = { ...row };
  validatingVisible.value = true;
}

//关闭展示弹窗
function handleValidatingClose() {
  ElMessageBox.confirm("确定要关闭吗？")
    .then(() => {
      validatingVisible.value = false;
    })
    .catch(() => {
      // catch error
    });
}

// 按钮加载标志
const validateLoadFlag = ref(false);

function handleValidateSubmit(flag: boolean) {
  //审核不通过
  if (!flag) {
    failVisible.value = true;
    return;
  }
  //开始加载
  validateLoadFlag.value = true;
  BusinessControllerService.updateBusinessStaticUsingPut({
    id: selectData.value.id,
    status: 3,
  })
    .then((res) => {
      //关闭弹窗
      validatingVisible.value = false;
      ElMessage.success(res.data);
      // 重新刷新数据
      handleQuery({}, true);
    })
    .finally(() => {
      validateLoadFlag.value = false;
    });
}

const failVisible = ref(false);
const connect = ref<string>();

function handleFailSubmit() {
  if (connect.value?.trim().length == 0) {
    ElMessage.warning("请输入失败理由！");
    return;
  }
  validateLoadFlag.value = true;
  BusinessControllerService.updateBusinessStaticUsingPut({
    id: selectData.value.id,
    status: 2,
    failMsg: connect.value,
  })
    .then((res) => {
      //关闭弹窗
      failVisible.value = false;
      validatingVisible.value = false;
      ElMessage.success(res.data);
    })
    .finally(() => {
      validateLoadFlag.value = false;
    });
}

// 3、审核商家内容结束
// 4、删除一条商家数据

const handleDel = (id: number) => {
  if (!id) {
    ElMessage.warning("请选择数据后再删除！");
    return;
  }
  //删除数据
  BusinessControllerService.delBusinessUsingDelete([id]).then((res) => {
    ElMessage.success(res.data);
    handleQuery({}, true);
  });
};
</script>

<style lang="scss" scoped>
#businessManage {
  .toolbar {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .pagination {
    margin-top: 12px;
  }
}
</style>
